import { Component, ChangeDetectorRef, ChangeDetectionStrategy } from "@angular/core";
import { SliderLevelModel } from "../../../../../../../shared/components/slider/sliderLevel.model";
import { BaseCriteriaTemplateComponent } from "../baseType.component";
import { ReportingService } from "../../../../../reporting.service";
import { Subscription, Observable } from "rxjs";
import { ICriteriaTemplate, TemplateType } from "../../models/criteriaTemplate.interface";
import { ICriteriaOutput } from "../../models/save/criteriaOutput.interface";
import { InvolvementOutput, InvolvementCategoryOutput } from "../../models/save/criteriaOutput.model";

@Component({
    selector: 'type4',
    templateUrl: 'type4.component.html',
    styleUrls: ['../../templateCriteria.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    providers: [{ provide: BaseCriteriaTemplateComponent, useExisting: Type4Component }]
})
export class Type4Component extends BaseCriteriaTemplateComponent implements ICriteriaTemplate {
    private sub: Subscription;
    public symbol: string;
    public sreenOnAnyInvolvement: boolean;
    public categories: any[];

    public levels: SliderLevelModel[] = [
        new SliderLevelModel(0, 'Off'),
        new SliderLevelModel(1, '100 - 50.0%', undefined, undefined, 'type4Pip', 50),
        new SliderLevelModel(2, '49.9 - 25.0%', undefined, undefined, 'type4Pip', 25),
        new SliderLevelModel(3, '24.9 - 10%', undefined, undefined, 'type4Pip', 10),
        new SliderLevelModel(4, '9.9 - 5%', undefined, undefined, 'type4Pip', 5),
        new SliderLevelModel(5, '4.9% - 0%', undefined, undefined, 'type4Pip', 0)
    ];
    public type: TemplateType = TemplateType.Involvement;

    constructor(
        private cdRef: ChangeDetectorRef,
        private toolsService: ReportingService) {
        super(toolsService, cdRef);
    }

    ngOnInit() {
        //get indicator symbol
        this.symbol = this.templateCriteria.criteriaEntityField.split(' ')[0];        
        if (this.edit == 'true') {
            this.loadInvolvementData();
            this.sub = this.load.subscribe(data => {
                this.categories = data || [];
                //convert selected values to level ids so the slider preselects them
                this.categories.forEach(category => {
                    category.selectedValue = category.selectedValue > -1 ? this.levels.find(x => x.value == category.selectedValue).id : 0;
                });
                this.cdRef.markForCheck();
            });
        }
        else
        {
            let func: Observable<any[]> = this.param == "SP" ? this.toolsService.getSustainableProductsCategories(this.symbol): this.toolsService.getInvolvementCategories(this.symbol);
            this.sub = func.subscribe(categories => {
                this.categories = categories;
                this.cdRef.markForCheck();
            });
        }
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
    }

    public sliderChanged(model: any, category: any) {
        category.selectedValue = model.id;
        BaseCriteriaTemplateComponent.changed.emit(this.anySelected());
    }

    public toggleInvolvement() {
        this.sreenOnAnyInvolvement = false;
        BaseCriteriaTemplateComponent.changed.emit(this.anySelected());
    }

    public toggleOwnership() {
        this.sreenOnAnyInvolvement = false;
        BaseCriteriaTemplateComponent.changed.emit(this.anySelected());
    }

    private anySelected(): boolean{
        return this.categories.findIndex(x => x.selectedValue > 0 || x.isInvolved == true || x.isSignificantOwnership == true) > -1;
    }

    public hasMultiple(category: any, index: number): boolean {
        let ret: boolean = index < this.categories.length - 1;

        if (ret && this.categories[index + 1].revenueRange.length == 0) {
            //if current and next selected category is involved or is significant ownership
            ret = (category.isInvolved || category.isSignificantOwnership) && (this.categories[index + 1].isInvolved || this.categories[index + 1].isSignificantOwnership);
        } else if (ret && this.categories[index + 1].revenueRange.length > 0) {
            //if current is significant ownership or has a selected value on the slider
            ret = (category.isSignificantOwnership || category.selectedValue > 0) && (this.categories[index + 1].isSignificantOwnership || this.categories[index + 1].selectedValue > 0);
        }

        return ret;
    }

    public hasAnyInvolvement(): boolean {
        let index = this.categories.findIndex(x =>
            (x.revenueRange.length == 0 && (x.isInvolved || x.isSignificantOwnership)) ||
            (x.revenueRange.length > 0 && (x.selectedValue > 0 || x.isSignificantOwnership))
        );
        return index != -1;
    }

    public anyInvolvementCheck() {
        this.categories.forEach(category => {
            if (category.significantOwnershipYesNo)
                category.isSignificantOwnership = this.sreenOnAnyInvolvement;
            if (category.revenueRange.length == 0)
                category.isInvolved = this.sreenOnAnyInvolvement;
            if (category.revenueRange.length > 0)
                category.selectedValue = this.sreenOnAnyInvolvement ? category.maxValue : 0;
        });
        BaseCriteriaTemplateComponent.changed.emit(this.anySelected());
        this.cdRef.markForCheck();
    }

    public filterLevels(levels: SliderLevelModel[], max: number): SliderLevelModel[]{
        return levels.filter(x=>x.id <= max);
    }

    public save(): ICriteriaOutput {
        let selectedCategories: InvolvementCategoryOutput[] = [];
        this.categories.forEach(category => {
            if (category.isInvolved || category.isSignificantOwnership || category.selectedValue > 0) {
                selectedCategories.push(new InvolvementCategoryOutput(
                    category.templateCriteriaId,
                    category.categoryOfInvolvement,
                    category.isSignificantOwnership,
                    category.isInvolved,
                    category.selectedValue > 0,
                    category.selectedValue > 0 ? category.revenueRange[5 - category.selectedValue].start : 0,
                    category.selectedValue > 0 ? category.revenueRange[5 - category.selectedValue].stop : 0,
                    category.categorySymbol
                ));
            }
        });

        return new InvolvementOutput(this.symbol, selectedCategories);
    }
}